<html>
 <head>
  <meta charset="UTF-8">
 </head>
 <body>
  <h3 data-lake-id="8e1b944f" id="8e1b944f"><span data-lake-id="u189a538b" id="u189a538b">背景</span></h3>
  <p data-lake-id="ubf9886fd" id="ubf9886fd"><br></p>
  <p data-lake-id="uf6d1e5f4" id="uf6d1e5f4"><span data-lake-id="udade92a2" id="udade92a2">在很多大型网站中，某些数据（比如热门文章、热点商品详情等）可能会成为热点，经常被大量用户请求。这可能导致数据库压力过大，进而使接口响应时间变长。为了应对这一问题，我们采取了一系列措施来减轻数据库负担，并提高接口的响应速度。</span></p>
  <p data-lake-id="ubf361612" id="ubf361612"><span data-lake-id="u10780874" id="u10780874">​</span><br></p>
  <p data-lake-id="u9a0bddcb" id="u9a0bddcb"><span data-lake-id="u55f73f25" id="u55f73f25">主要采用了有效的缓存策略和异步处理技术来减轻数据库负担并提高接口响应速度。</span></p>
  <p data-lake-id="uef3608b8" id="uef3608b8"><span data-lake-id="ub7960462" id="ub7960462">​</span><br></p>
  <p data-lake-id="u0d540bb4" id="u0d540bb4"><span data-lake-id="u715026b9" id="u715026b9">以下演示的是我们需要提供一个电商平台的商品详情接口，该接口需要执行以下操作：</span></p>
  <ol list="u101650fd">
   <li fid="uba988e6b" data-lake-id="ua24aca4c" id="ua24aca4c"><span data-lake-id="u5aef4428" id="u5aef4428">获取商品的基本信息。</span></li>
   <li fid="uba988e6b" data-lake-id="u609f7108" id="u609f7108"><span data-lake-id="u003ef8a0" id="u003ef8a0">获取商品的用户评论。</span></li>
   <li fid="uba988e6b" data-lake-id="u61f2b40f" id="u61f2b40f"><span data-lake-id="u3b5dccb8" id="u3b5dccb8">获取推荐商品列表。</span></li>
  </ol>
  <p data-lake-id="ud8d6231a" id="ud8d6231a"><br></p>
  <h3 data-lake-id="15a472cc" id="15a472cc"><span data-lake-id="u8f2282b8" id="u8f2282b8">技术选型</span></h3>
  <p data-lake-id="u7098052f" id="u7098052f"><br></p>
  <p data-lake-id="u1702fed2" id="u1702fed2"><span data-lake-id="ueeee6609" id="ueeee6609">这里面商品的基本信息和商品的评论信息我们可以适当的做一些数据预热。</span></p>
  <p data-lake-id="u90296608" id="u90296608"><br></p>
  <p data-lake-id="uf257ce3f" id="uf257ce3f"><span data-lake-id="u5467f1c3" id="u5467f1c3">数据预热基本上是要基于缓存的，缓存有很多种，本地缓存，分布式缓存等，这里我们选择了目前市面上比较常用的本地缓存+分布式缓存实现二级缓存。</span></p>
  <p data-lake-id="u21fda644" id="u21fda644"><span data-lake-id="u0d086b3f" id="u0d086b3f">​</span><br></p>
  <p data-lake-id="ub77cb6fa" id="ub77cb6fa"><span data-lake-id="u0e1cf57c" id="u0e1cf57c">本地缓存主要选择Caffeine，主要是因为Caffeine 提供了接近最优的性能，是当前 Java 中最快的缓存库之一。支持时间和大小驱逐策略，以及同步和异步加载等。同时也是Spring官方推荐的缓存框架。</span></p>
  <p data-lake-id="uc16aefec" id="uc16aefec"><span data-lake-id="u40f70ef4" id="u40f70ef4">​</span><br></p>
  <p data-lake-id="u1f79ad7f" id="u1f79ad7f"><span data-lake-id="ub8afe69e" id="ub8afe69e">分布式缓存采用的是主流的Redis。</span></p>
  <p data-lake-id="u7bdc298f" id="u7bdc298f"><span data-lake-id="ud0f0b068" id="ud0f0b068">​</span><br></p>
  <p data-lake-id="u9dec3f63" id="u9dec3f63"><span data-lake-id="u2ca27ecd" id="u2ca27ecd">异步化编程这里直接使用 Java 的 </span><code data-lake-id="u297657dd" id="u297657dd"><span data-lake-id="u914344d0" id="u914344d0">CompletableFuture</span></code><span data-lake-id="ud8b6993c" id="ud8b6993c"> 或 Spring 的 </span><code data-lake-id="u9188c320" id="u9188c320"><span data-lake-id="udc99d28a" id="udc99d28a">@Async</span></code><span data-lake-id="ua2b98fdc" id="ua2b98fdc"> 注解实现异步处理，以优化耗时操作。</span></p>
  <p data-lake-id="u64ecaf76" id="u64ecaf76"><br></p>
  <h3 data-lake-id="380cf2b5" id="380cf2b5"><span data-lake-id="ud2350d03" id="ud2350d03">具体实现</span></h3>
  <p data-lake-id="ud1c8ca63" id="ud1c8ca63"><br></p>
  <h4 data-lake-id="b3d9fa62" id="b3d9fa62"><span data-lake-id="u3337c3e2" id="u3337c3e2">Caffeine 缓存配置</span></h4>
  <p data-lake-id="u9fd44f18" id="u9fd44f18"><br></p>
  <pre lang="java"><code>
@Configuration
public class CacheConfig {

    @Bean
    public CacheManager cacheManager() {
        CaffeineCacheManager cacheManager = new CaffeineCacheManager("dataCache");
        cacheManager.setCaffeine(caffeineCacheBuilder());
        return cacheManager;
    }

    Caffeine&lt;Object, Object&gt; caffeineCacheBuilder() {
        return Caffeine.newBuilder()
                .initialCapacity(100)
                .maximumSize(1000)
                .expireAfterWrite(10, TimeUnit.MINUTES)
                .weakKeys()
                .recordStats();
    }
}
</code></pre>
  <p data-lake-id="u799704d5" id="u799704d5"><br></p>
  <h4 data-lake-id="e20c9e05" id="e20c9e05"><span data-lake-id="u1e98a6f3" id="u1e98a6f3">二级缓存实现</span></h4>
  <p data-lake-id="ue7232f63" id="ue7232f63"><br></p>
  <pre lang="java"><code>
@Service
public class DataService {

    @Autowired
    private CacheManager caffeineCacheManager;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public Object getData(String key) {
        // 尝试从 Caffeine 缓存获取
        Cache caffeineCache = caffeineCacheManager.getCache("dataCache");
        Object value = caffeineCache.getIfPresent(key);

        if (value == null) {
            // 尝试从 Redis 缓存获取
            value = redisTemplate.opsForValue().get(key);
            if (value == null) {
                // 缓存未命中，从数据库加载
                value = loadDataFromDB(key);
                redisTemplate.opsForValue().set(key, value);
            }
            caffeineCache.put(key, value);
        }

        return value;
    }

    private Object loadDataFromDB(String key

</code></pre>
  <p data-lake-id="uf645f55b" id="uf645f55b"><br></p>
  <p data-lake-id="ua6e803ca" id="ua6e803ca"><br></p>
  <p data-lake-id="u53b1f0e5" id="u53b1f0e5"><span data-lake-id="u5060518a" id="u5060518a">整个ProductService的实现：</span></p>
  <p data-lake-id="u958345ac" id="u958345ac"><span data-lake-id="u3919138f" id="u3919138f">​</span><br></p>
  <p data-lake-id="u5c4eafcd" id="u5c4eafcd"><strong><span data-lake-id="ud9bb9053" id="ud9bb9053">这里我们使用 </span></strong><code data-lake-id="uf358d4c3" id="uf358d4c3"><strong><span data-lake-id="u9cc7af86" id="u9cc7af86">CompletableFuture</span></strong></code><span data-lake-id="u5d3c3f15" id="u5d3c3f15">， 提供了丰富的 API 来处理异步操作和转换结果。可以用来优化后台任务，比如数据的异步加载和处理。</span></p>
  <p data-lake-id="uc152bc37" id="uc152bc37"><span data-lake-id="u2a22b803" id="u2a22b803">​</span><br></p>
  <pre lang="java"><code>
@Service
public class ProductService {

    @Autowired
    private CacheManager caffeineCacheManager;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public CompletableFuture&lt;Product&gt; getProductDetails(String productId) {
        return CompletableFuture.completedFuture(getCachedProduct(productId));
    }

    public CompletableFuture&lt;List&lt;Review&gt;&gt; getProductReviews(String productId) {
        return CompletableFuture.completedFuture(getCachedReviews(productId));
    }

    public CompletableFuture&lt;List&lt;Product&gt;&gt; getRecommendedProducts(String productId) {
        // 模拟数据库查询
        return CompletableFuture.completedFuture(queryRecommendations(productId));
    }


    private Product getCachedProduct(String productId) {
        return getCachedData("productCache", productId, this::queryProduct);
    }

    private List&lt;Review&gt; getCachedReviews(String productId) {
        return getCachedData("reviewsCache", productId, this::queryReviews);
    }

    private &lt;T&gt; T getCachedData(String cacheName, String key, Function&lt;String, T&gt; dbQuery) {
        // 尝试从 Caffeine 缓存获取
        Cache caffeineCache = caffeineCacheManager.getCache(cacheName);
        T value = caffeineCache.getIfPresent(key, T.class);
        
        if (value == null) {
            // 尝试从 Redis 缓存获取
            String cachedData = redisTemplate.opsForValue().get(key);
            if (cachedData != null) {
                value = convertStringToObject(cachedData, T.class); // 将字符串转换为对象
            } else {
                // 缓存未命中，从数据库加载
                value = dbQuery.apply(key);
                redisTemplate.opsForValue().set(key, convertObjectToString(value)); // 缓存结果
            }
            caffeineCache.put(key, value);
        }

        return value;
    }

    private Product queryProduct(String productId) {
        // 从数据库查询商品详情逻辑
    }

    private List&lt;Review&gt; queryReviews(String productId) {
        // 从数据库查询用户评论逻辑
    }

  	    private List&lt;Product&gt; queryRecommendations(String productId) {
        // 从数据库查询推荐商品逻辑
    }
    
}

</code></pre>
  <p data-lake-id="u574c5e38" id="u574c5e38"><br></p>
  <p data-lake-id="u947dc531" id="u947dc531"><br></p>
  <p data-lake-id="u4962ca5a" id="u4962ca5a"><span data-lake-id="uf6d18ba2" id="uf6d18ba2">编排及结果汇总：</span></p>
  <p data-lake-id="ucdba53d6" id="ucdba53d6"><span data-lake-id="udd5a2150" id="udd5a2150">​</span><br></p>
  <pre lang="java"><code>
@RestController
@RequestMapping("/products")
public class ProductController {

    @Autowired
    private ProductService productService;

    @GetMapping("/{productId}")
    public CompletableFuture&lt;ProductDetail&gt; getProductDetail(@PathVariable String productId) {
        CompletableFuture&lt;Product&gt; productFuture = productService.getProductDetails(productId);
        CompletableFuture&lt;List&lt;Review&gt;&gt; reviewsFuture = productService.getProductReviews(productId);
        CompletableFuture&lt;List&lt;Product&gt;&gt; recommendationsFuture = productService.getRecommendedProducts(productId);

        return CompletableFuture.allOf(productFuture, reviewsFuture, recommendationsFuture)
                .thenApply(v -&gt; {
                    Product product = productFuture.join();
                    List&lt;Review&gt; reviews = reviewsFuture.join();
                    List&lt;Product&gt; recommendations = recommendationsFuture.join();
                    return new ProductDetail(product, reviews, recommendations);
                });
    }
}


public class ProductDetail {
    private Product product;
    private List&lt;Review&gt; reviews;
    private List&lt;Product&gt; recommendations;

    // 构造函数、getter 和 setter
}
</code></pre>
  <p data-lake-id="ucbf69176" id="ucbf69176"><strong><span data-lake-id="uc8e4c077" id="uc8e4c077">​</span></strong><br></p>
  <p data-lake-id="ud7cd5406" id="ud7cd5406"><br></p>
  <p data-lake-id="u27e81ebb" id="u27e81ebb"><span data-lake-id="u8f1421ca" id="u8f1421ca">以上方案，还存在两个问题没有考虑：</span></p>
  <p data-lake-id="u5035edb0" id="u5035edb0"><br></p>
  <ul list="u55fced62">
   <li fid="u81abcda0" data-lake-id="uf07377ab" id="uf07377ab"><strong><span data-lake-id="u95880329" id="u95880329">1、缓存一致性</span></strong><span data-lake-id="u42e03b87" id="u42e03b87">：如何确保在数据更新时同步更新或清除缓存，如何做到缓存失效</span></li>
   <li fid="u81abcda0" data-lake-id="uc595da8e" id="uc595da8e"><strong><span data-lake-id="u07ca8d16" id="u07ca8d16">2、异常处理</span></strong><span data-lake-id="ua93a0f00" id="ua93a0f00">：在使用 CompletableFuture 时，应该考虑异常处理策略，例如使用 exceptionally 方法来处理异常情况。</span></li>
  </ul>
  <p data-lake-id="u70a0c578" id="u70a0c578"><br></p>
  <p data-lake-id="u133c3429" id="u133c3429"><span data-lake-id="u72241b74" id="u72241b74">接着优化。</span></p>
  <p data-lake-id="u45a7076b" id="u45a7076b"><span data-lake-id="ucf28caf5" id="ucf28caf5">​</span><br></p>
  <h4 data-lake-id="C2MJB" id="C2MJB"><span data-lake-id="udc9f531d" id="udc9f531d">异常处理</span></h4>
  <p data-lake-id="u3e7f48ff" id="u3e7f48ff"><br></p>
  <p data-lake-id="u6571f094" id="u6571f094"><span data-lake-id="ucf1e1fc0" id="ucf1e1fc0">在使用 CompletableFuture 时，可以使用 exceptionally 方法来处理异常情况。此外，还可以使用 handle 方法，它能够同时处理正常的结果和异常情况。</span></p>
  <p data-lake-id="u9eafaa08" id="u9eafaa08"><span data-lake-id="u980b341e" id="u980b341e">​</span><br></p>
  <pre lang="java"><code>
@Service
public class ProductService {

    // ... 其他方法 ...

    @Async
    public CompletableFuture&lt;Product&gt; getProductDetails(String productId) {
        return CompletableFuture
                .supplyAsync(() -&gt; getCachedProduct(productId))
                .exceptionally(ex -&gt; handleException("getProductDetails", productId, ex));
    }

    @Async
    public CompletableFuture&lt;List&lt;Review&gt;&gt; getProductReviews(String productId) {
        return CompletableFuture
                .supplyAsync(() -&gt; getCachedReviews(productId))
                .exceptionally(ex -&gt; handleException("getProductReviews", productId, ex));
    }

    private &lt;T&gt; T handleException(String methodName, String key, Throwable ex) {
        // 记录日志
        log.error("Error in " + methodName + " for key " + key, ex);
        // 可以返回一个默认值或 null，或者重新抛出异常
        return null;
    }
}
</code></pre>
  <p data-lake-id="u3477e929" id="u3477e929"><br></p>
  <p data-lake-id="u7107797a" id="u7107797a"><br></p>
  <h4 data-lake-id="ycH3Z" id="ycH3Z"><span data-lake-id="ucc172322" id="ucc172322">缓存一致性</span></h4>
  <p data-lake-id="u0f9c44db" id="u0f9c44db"><br></p>
  <p data-lake-id="ucc9fbfa1" id="ucc9fbfa1"><span data-lake-id="u17f0136e" id="u17f0136e">保证缓存一致性，有很多方案，我们可以采用延迟双删的方案，也可以采用cache aside的方案。这里用延迟双删实现。</span></p>
  <p data-lake-id="u8f0f0656" id="u8f0f0656"><span data-lake-id="u21a435c1" id="u21a435c1">​</span><br></p>
  <p data-lake-id="ue5914607" id="ue5914607"><span data-lake-id="u12a6c723" id="u12a6c723">我们使用 Spring 的 @Scheduled注解来实现定时任务做第二次的删除动作。</span></p>
  <p data-lake-id="u00bd7a40" id="u00bd7a40"><span data-lake-id="u0e199882" id="u0e199882">​</span><br></p>
  <p data-lake-id="udaf88512" id="udaf88512"><span data-lake-id="u324a6b5a" id="u324a6b5a">​</span><br></p>
  <pre lang="java"><code>
@Service
public class ProductService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    private final BlockingQueue&lt;String&gt; cacheDeletionQueue = new LinkedBlockingQueue&lt;&gt;();

    public void updateProduct(Product product) {
        // 第一次删除缓存
        deleteCache(product.getId());

        // 更新数据库
        updateProductInDB(product);

        // 添加到延迟删除队列
        cacheDeletionQueue.add(product.getId());
    }

    @Scheduled(fixedDelay = 100)
    public void delayedCacheDeletion() {
        String productId = cacheDeletionQueue.poll();
        if (productId != null) {
            deleteCache(productId);
        }
    }

    // ... 其他方法 ...
}

</code></pre>
  <p data-lake-id="u7d919e50" id="u7d919e50"><br></p>
  <p data-lake-id="ub950b0e4" id="ub950b0e4"><span data-lake-id="u4e17b5a0" id="u4e17b5a0">当然，这里使用@Scheduled也并不完美，一个是它是基于JVM内存的，一旦应用重启，任务就丢失了，还有就是他这里使用的是阻塞队列，如果任务太多也会有问题。</span></p>
  <p data-lake-id="u25651c00" id="u25651c00"><span data-lake-id="u1f47833e" id="u1f47833e">​</span><br></p>
  <p data-lake-id="ub9fb256f" id="ub9fb256f"><span data-lake-id="ueb05e10b" id="ueb05e10b">这里反正可以用MQ或者Redisson来实现延迟队列更完美一点，或者给予binlog监听做第二次删除也可以。</span></p>
  <p data-lake-id="uf89a596d" id="uf89a596d"><br></p>
  <p data-lake-id="uab10faae" id="uab10faae"><br></p>
  <h3 data-lake-id="uIVAZ" id="uIVAZ"><span data-lake-id="u4cc55487" id="u4cc55487">学习资料</span></h3>
  <p data-lake-id="u09918ec2" id="u09918ec2"><br></p>
  <p data-lake-id="u4b87006f" id="u4b87006f"><br></p>
  <p data-lake-id="u3baf4577" id="u3baf4577"><br></p>
  <p data-lake-id="u853fa0ad" id="u853fa0ad"><br></p>
  <p data-lake-id="u69078bd0" id="u69078bd0"><br></p>
 </body>
</html>